var cluster=require('cluster');
var numCPUs=require('os').cpus().length;
var http=require('http');
var workers={};
var requests=0;

if(cluster.isMaster){
    for(var i=0;i<numCPUs;i++){
        workers[i]=cluster.fork();
    }

    for(var i=0;i<numCPUs;i++){
        workers[i].on('message', function (msg) {
            console.log('in msg:',msg);
            if('in' == msg.cmd){
                requests++;
                for(var j=0;i<numCPUs;j++){
                    workers[j].send({
                        cmd:'update',
                        requests:requests
                    });
                }
            }
        });
    }

    cluster.on('exit', function (worker, code, signal) {
        console.log('Worker '+worker.process.pid + 'died.');
    });

}else{
    process.on('message', function (msg) {
        console.log('update msg:',msg);
        if('update' == msg.cmd){
            requests = msg.requests;
        }
    });
    http.createServer(function (req, res) {
        res.setHeader('Content-Type','text/plain;charset=utf-8');
        res.end('Worker in process ' + process.pid + ' says cluster has responded to '+ requests + ' requests.');
        process.send({cmd:'in'});
    }).listen(3000,function () {
        console.log('ToDoList 3000',new Date());
    });
}